home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / pickle.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  26.4 KB  |  987 lines

  1. """Create portable serialized representations of Python objects.
  2.  
  3. See module cPickle for a (much) faster implementation.
  4. See module copy_reg for a mechanism for registering custom picklers.
  5.  
  6. Classes:
  7.  
  8.     Pickler
  9.     Unpickler
  10.  
  11. Functions:
  12.  
  13.     dump(object, file)
  14.     dumps(object) -> string
  15.     load(file) -> object
  16.     loads(string) -> object
  17.  
  18. Misc variables:
  19.  
  20.     __version__
  21.     format_version
  22.     compatible_formats
  23.  
  24. """
  25.  
  26. __version__ = "$Revision: 1.56.4.4 $"       # Code version
  27.  
  28. from types import *
  29. from copy_reg import dispatch_table, safe_constructors
  30. import marshal
  31. import sys
  32. import struct
  33. import re
  34.  
  35. __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
  36.            "Unpickler", "dump", "dumps", "load", "loads"]
  37.  
  38. format_version = "1.3"                     # File format version we write
  39. compatible_formats = ["1.0", "1.1", "1.2"] # Old format versions we can read
  40.  
  41. mdumps = marshal.dumps
  42. mloads = marshal.loads
  43.  
  44. class PickleError(Exception): pass
  45. class PicklingError(PickleError): pass
  46. class UnpicklingError(PickleError): pass
  47.  
  48. class _Stop(Exception):
  49.     def __init__(self, value):
  50.         self.value = value
  51.  
  52. try:
  53.     from org.python.core import PyStringMap
  54. except ImportError:
  55.     PyStringMap = None
  56.  
  57. try:
  58.     UnicodeType
  59. except NameError:
  60.     UnicodeType = None
  61.  
  62.  
  63. MARK            = '('
  64. STOP            = '.'
  65. POP             = '0'
  66. POP_MARK        = '1'
  67. DUP             = '2'
  68. FLOAT           = 'F'
  69. INT             = 'I'
  70. BININT          = 'J'
  71. BININT1         = 'K'
  72. LONG            = 'L'
  73. BININT2         = 'M'
  74. NONE            = 'N'
  75. PERSID          = 'P'
  76. BINPERSID       = 'Q'
  77. REDUCE          = 'R'
  78. STRING          = 'S'
  79. BINSTRING       = 'T'
  80. SHORT_BINSTRING = 'U'
  81. UNICODE         = 'V'
  82. BINUNICODE      = 'X'
  83. APPEND          = 'a'
  84. BUILD           = 'b'
  85. GLOBAL          = 'c'
  86. DICT            = 'd'
  87. EMPTY_DICT      = '}'
  88. APPENDS         = 'e'
  89. GET             = 'g'
  90. BINGET          = 'h'
  91. INST            = 'i'
  92. LONG_BINGET     = 'j'
  93. LIST            = 'l'
  94. EMPTY_LIST      = ']'
  95. OBJ             = 'o'
  96. PUT             = 'p'
  97. BINPUT          = 'q'
  98. LONG_BINPUT     = 'r'
  99. SETITEM         = 's'
  100. TUPLE           = 't'
  101. EMPTY_TUPLE     = ')'
  102. SETITEMS        = 'u'
  103. BINFLOAT        = 'G'
  104.  
  105. __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$",x)])
  106.  
  107. class Pickler:
  108.  
  109.     def __init__(self, file, bin = 0):
  110.         self.write = file.write
  111.         self.memo = {}
  112.         self.bin = bin
  113.  
  114.     def dump(self, object):
  115.         self.save(object)
  116.         self.write(STOP)
  117.  
  118.     def put(self, i):
  119.         if self.bin:
  120.             s = mdumps(i)[1:]
  121.             if i < 256:
  122.                 return BINPUT + s[0]
  123.  
  124.             return LONG_BINPUT + s
  125.  
  126.         return PUT + `i` + '\n'
  127.  
  128.     def get(self, i):
  129.         if self.bin:
  130.             s = mdumps(i)[1:]
  131.  
  132.             if i < 256:
  133.                 return BINGET + s[0]
  134.  
  135.             return LONG_BINGET + s
  136.  
  137.         return GET + `i` + '\n'
  138.  
  139.     def save(self, object, pers_save = 0):
  140.         memo = self.memo
  141.  
  142.         if not pers_save:
  143.             pid = self.persistent_id(object)
  144.             if pid is not None:
  145.                 self.save_pers(pid)
  146.                 return
  147.  
  148.         d = id(object)
  149.  
  150.         t = type(object)
  151.  
  152.         if (t is TupleType) and (len(object) == 0):
  153.             if self.bin:
  154.                 self.save_empty_tuple(object)
  155.             else:
  156.                 self.save_tuple(object)
  157.             return
  158.  
  159.         if memo.has_key(d):
  160.             self.write(self.get(memo[d][0]))
  161.             return
  162.  
  163.         try:
  164.             f = self.dispatch[t]
  165.         except KeyError:
  166.             pid = self.inst_persistent_id(object)
  167.             if pid is not None:
  168.                 self.save_pers(pid)
  169.                 return
  170.  
  171.             try:
  172.                 issc = issubclass(t, TypeType)
  173.             except TypeError: # t is not a class
  174.                 issc = 0
  175.             if issc:
  176.                 self.save_global(object)
  177.                 return
  178.  
  179.             try:
  180.                 reduce = dispatch_table[t]
  181.             except KeyError:
  182.                 try:
  183.                     reduce = object.__reduce__
  184.                 except AttributeError:
  185.                     raise PicklingError, \
  186.                         "can't pickle %s object: %s" % (`t.__name__`,
  187.                                                          `object`)
  188.                 else:
  189.                     tup = reduce()
  190.             else:
  191.                 tup = reduce(object)
  192.  
  193.             if type(tup) is StringType:
  194.                 self.save_global(object, tup)
  195.                 return
  196.  
  197.             if type(tup) is not TupleType:
  198.                 raise PicklingError, "Value returned by %s must be a " \
  199.                                      "tuple" % reduce
  200.  
  201.             l = len(tup)
  202.  
  203.             if (l != 2) and (l != 3):
  204.                 raise PicklingError, "tuple returned by %s must contain " \
  205.                                      "only two or three elements" % reduce
  206.  
  207.             callable = tup[0]
  208.             arg_tup  = tup[1]
  209.  
  210.             if l > 2:
  211.                 state = tup[2]
  212.             else:
  213.                 state = None
  214.  
  215.             if type(arg_tup) is not TupleType and arg_tup is not None:
  216.                 raise PicklingError, "Second element of tuple returned " \
  217.                                      "by %s must be a tuple" % reduce
  218.  
  219.             self.save_reduce(callable, arg_tup, state)
  220.             memo_len = len(memo)
  221.             self.write(self.put(memo_len))
  222.             memo[d] = (memo_len, object)
  223.             return
  224.  
  225.         f(self, object)
  226.  
  227.     def persistent_id(self, object):
  228.         return None
  229.  
  230.     def inst_persistent_id(self, object):
  231.         return None
  232.  
  233.     def save_pers(self, pid):
  234.         if not self.bin:
  235.             self.write(PERSID + str(pid) + '\n')
  236.         else:
  237.             self.save(pid, 1)
  238.             self.write(BINPERSID)
  239.  
  240.     def save_reduce(self, callable, arg_tup, state = None):
  241.         write = self.write
  242.         save = self.save
  243.  
  244.         save(callable)
  245.         save(arg_tup)
  246.         write(REDUCE)
  247.  
  248.         if state is not None:
  249.             save(state)
  250.             write(BUILD)
  251.  
  252.     dispatch = {}
  253.  
  254.     def save_none(self, object):
  255.         self.write(NONE)
  256.     dispatch[NoneType] = save_none
  257.  
  258.     def save_int(self, object):
  259.         if self.bin:
  260.             # If the int is small enough to fit in a signed 4-byte 2's-comp
  261.             # format, we can store it more efficiently than the general
  262.             # case.
  263.             high_bits = object >> 31  # note that Python shift sign-extends
  264.             if  high_bits == 0 or high_bits == -1:
  265.                 # All high bits are copies of bit 2**31, so the value
  266.                 # fits in a 4-byte signed int.
  267.                 i = mdumps(object)[1:]
  268.                 assert len(i) == 4
  269.                 if i[-2:] == '\000\000':    # fits in 2-byte unsigned int
  270.                     if i[-3] == '\000':     # fits in 1-byte unsigned int
  271.                         self.write(BININT1 + i[0])
  272.                     else:
  273.                         self.write(BININT2 + i[:2])
  274.                 else:
  275.                     self.write(BININT + i)
  276.                 return
  277.         # Text pickle, or int too big to fit in signed 4-byte format.
  278.         self.write(INT + `object` + '\n')
  279.     dispatch[IntType] = save_int
  280.  
  281.     def save_long(self, object):
  282.         self.write(LONG + `object` + '\n')
  283.     dispatch[LongType] = save_long
  284.  
  285.     def save_float(self, object, pack=struct.pack):
  286.         if self.bin:
  287.             self.write(BINFLOAT + pack('>d', object))
  288.         else:
  289.             self.write(FLOAT + `object` + '\n')
  290.     dispatch[FloatType] = save_float
  291.  
  292.     def save_string(self, object):
  293.         d = id(object)
  294.         memo = self.memo
  295.  
  296.         if self.bin:
  297.             l = len(object)
  298.             s = mdumps(l)[1:]
  299.             if l < 256:
  300.                 self.write(SHORT_BINSTRING + s[0] + object)
  301.             else:
  302.                 self.write(BINSTRING + s + object)
  303.         else:
  304.             self.write(STRING + `object` + '\n')
  305.  
  306.         memo_len = len(memo)
  307.         self.write(self.put(memo_len))
  308.         memo[d] = (memo_len, object)
  309.     dispatch[StringType] = save_string
  310.  
  311.     def save_unicode(self, object):
  312.         d = id(object)
  313.         memo = self.memo
  314.  
  315.         if self.bin:
  316.             encoding = object.encode('utf-8')
  317.             l = len(encoding)
  318.             s = mdumps(l)[1:]
  319.             self.write(BINUNICODE + s + encoding)
  320.         else:
  321.             object = object.replace("\\", "\\u005c")
  322.             object = object.replace("\n", "\\u000a")
  323.             self.write(UNICODE + object.encode('raw-unicode-escape') + '\n')
  324.  
  325.         memo_len = len(memo)
  326.         self.write(self.put(memo_len))
  327.         memo[d] = (memo_len, object)
  328.     dispatch[UnicodeType] = save_unicode
  329.  
  330.     if StringType == UnicodeType:
  331.         # This is true for Jython
  332.         def save_string(self, object):
  333.             d = id(object)
  334.             memo = self.memo
  335.             unicode = object.isunicode()
  336.  
  337.             if self.bin:
  338.                 if unicode:
  339.                     object = object.encode("utf-8")
  340.                 l = len(object)
  341.                 s = mdumps(l)[1:]
  342.                 if l < 256 and not unicode:
  343.                     self.write(SHORT_BINSTRING + s[0] + object)
  344.                 else:
  345.                     if unicode:
  346.                         self.write(BINUNICODE + s + object)
  347.                     else:
  348.                         self.write(BINSTRING + s + object)
  349.             else:
  350.                 if unicode:
  351.                     object = object.replace("\\", "\\u005c")
  352.                     object = object.replace("\n", "\\u000a")
  353.                     object = object.encode('raw-unicode-escape')
  354.                     self.write(UNICODE + object + '\n')
  355.                 else:
  356.                     self.write(STRING + `object` + '\n')
  357.  
  358.             memo_len = len(memo)
  359.             self.write(self.put(memo_len))
  360.             memo[d] = (memo_len, object)
  361.         dispatch[StringType] = save_string
  362.  
  363.     def save_tuple(self, object):
  364.  
  365.         write = self.write
  366.         save  = self.save
  367.         memo  = self.memo
  368.  
  369.         d = id(object)
  370.  
  371.         write(MARK)
  372.  
  373.         for element in object:
  374.             save(element)
  375.  
  376.         if len(object) and memo.has_key(d):
  377.             if self.bin:
  378.                 write(POP_MARK + self.get(memo[d][0]))
  379.                 return
  380.  
  381.             write(POP * (len(object) + 1) + self.get(memo[d][0]))
  382.             return
  383.  
  384.         memo_len = len(memo)
  385.         self.write(TUPLE + self.put(memo_len))
  386.         memo[d] = (memo_len, object)
  387.     dispatch[TupleType] = save_tuple
  388.  
  389.     def save_empty_tuple(self, object):
  390.         self.write(EMPTY_TUPLE)
  391.  
  392.     def save_list(self, object):
  393.         d = id(object)
  394.  
  395.         write = self.write
  396.         save  = self.save
  397.         memo  = self.memo
  398.  
  399.         if self.bin:
  400.             write(EMPTY_LIST)
  401.         else:
  402.             write(MARK + LIST)
  403.  
  404.         memo_len = len(memo)
  405.         write(self.put(memo_len))
  406.         memo[d] = (memo_len, object)
  407.  
  408.         using_appends = (self.bin and (len(object) > 1))
  409.  
  410.         if using_appends:
  411.             write(MARK)
  412.  
  413.         for element in object:
  414.             save(element)
  415.  
  416.             if not using_appends:
  417.                 write(APPEND)
  418.  
  419.         if using_appends:
  420.             write(APPENDS)
  421.     dispatch[ListType] = save_list
  422.  
  423.     def save_dict(self, object):
  424.         d = id(object)
  425.  
  426.         write = self.write
  427.         save  = self.save
  428.         memo  = self.memo
  429.  
  430.         if self.bin:
  431.             write(EMPTY_DICT)
  432.         else:
  433.             write(MARK + DICT)
  434.  
  435.         memo_len = len(memo)
  436.         self.write(self.put(memo_len))
  437.         memo[d] = (memo_len, object)
  438.  
  439.         using_setitems = (self.bin and (len(object) > 1))
  440.  
  441.         if using_setitems:
  442.             write(MARK)
  443.  
  444.         items = object.items()
  445.         for key, value in items:
  446.             save(key)
  447.             save(value)
  448.  
  449.             if not using_setitems:
  450.                 write(SETITEM)
  451.  
  452.         if using_setitems:
  453.             write(SETITEMS)
  454.  
  455.     dispatch[DictionaryType] = save_dict
  456.     if not PyStringMap is None:
  457.         dispatch[PyStringMap] = save_dict
  458.  
  459.     def save_inst(self, object):
  460.         d = id(object)
  461.         cls = object.__class__
  462.  
  463.         memo  = self.memo
  464.         write = self.write
  465.         save  = self.save
  466.  
  467.         if hasattr(object, '__getinitargs__'):
  468.             args = object.__getinitargs__()
  469.             len(args) # XXX Assert it's a sequence
  470.             _keep_alive(args, memo)
  471.         else:
  472.             args = ()
  473.  
  474.         write(MARK)
  475.  
  476.         if self.bin:
  477.             save(cls)
  478.  
  479.         for arg in args:
  480.             save(arg)
  481.  
  482.         memo_len = len(memo)
  483.         if self.bin:
  484.             write(OBJ + self.put(memo_len))
  485.         else:
  486.             write(INST + cls.__module__ + '\n' + cls.__name__ + '\n' +
  487.                 self.put(memo_len))
  488.  
  489.         memo[d] = (memo_len, object)
  490.  
  491.         try:
  492.             getstate = object.__getstate__
  493.         except AttributeError:
  494.             stuff = object.__dict__
  495.         else:
  496.             stuff = getstate()
  497.             _keep_alive(stuff, memo)
  498.         save(stuff)
  499.         write(BUILD)
  500.     dispatch[InstanceType] = save_inst
  501.  
  502.     def save_global(self, object, name = None):
  503.         write = self.write
  504.         memo = self.memo
  505.  
  506.         if name is None:
  507.             name = object.__name__
  508.  
  509.         try:
  510.             module = object.__module__
  511.         except AttributeError:
  512.             module = whichmodule(object, name)
  513.  
  514.         try:
  515.             __import__(module)
  516.             mod = sys.modules[module]
  517.             klass = getattr(mod, name)
  518.         except (ImportError, KeyError, AttributeError):
  519.             raise PicklingError(
  520.                 "Can't pickle %r: it's not found as %s.%s" %
  521.                 (object, module, name))
  522.         else:
  523.             if klass is not object:
  524.                 raise PicklingError(
  525.                     "Can't pickle %r: it's not the same object as %s.%s" %
  526.                     (object, module, name))
  527.  
  528.         memo_len = len(memo)
  529.         write(GLOBAL + module + '\n' + name + '\n' +
  530.             self.put(memo_len))
  531.         memo[id(object)] = (memo_len, object)
  532.     dispatch[ClassType] = save_global
  533.     dispatch[FunctionType] = save_global
  534.     dispatch[BuiltinFunctionType] = save_global
  535.     dispatch[TypeType] = save_global
  536.  
  537.  
  538. def _keep_alive(x, memo):
  539.     """Keeps a reference to the object x in the memo.
  540.  
  541.     Because we remember objects by their id, we have
  542.     to assure that possibly temporary objects are kept
  543.     alive by referencing them.
  544.     We store a reference at the id of the memo, which should
  545.     normally not be used unless someone tries to deepcopy
  546.     the memo itself...
  547.     """
  548.     try:
  549.         memo[id(memo)].append(x)
  550.     except KeyError:
  551.         # aha, this is the first one :-)
  552.         memo[id(memo)]=[x]
  553.  
  554.  
  555. classmap = {} # called classmap for backwards compatibility
  556.  
  557. def whichmodule(func, funcname):
  558.     """Figure out the module in which a function occurs.
  559.  
  560.     Search sys.modules for the module.
  561.     Cache in classmap.
  562.     Return a module name.
  563.     If the function cannot be found, return __main__.
  564.     """
  565.     if classmap.has_key(func):
  566.         return classmap[func]
  567.  
  568.     for name, module in sys.modules.items():
  569.         if module is None:
  570.             continue # skip dummy package entries
  571.         if name != '__main__' and \
  572.             hasattr(module, funcname) and \
  573.             getattr(module, funcname) is func:
  574.             break
  575.     else:
  576.         name = '__main__'
  577.     classmap[func] = name
  578.     return name
  579.  
  580.  
  581. class Unpickler:
  582.  
  583.     def __init__(self, file):
  584.         self.readline = file.readline
  585.         self.read = file.read
  586.         self.memo = {}
  587.  
  588.     def load(self):
  589.         self.mark = object() # any new unique object
  590.         self.stack = []
  591.         self.append = self.stack.append
  592.         read = self.read
  593.         dispatch = self.dispatch
  594.         try:
  595.             while 1:
  596.                 key = read(1)
  597.                 dispatch[key](self)
  598.         except _Stop, stopinst:
  599.             return stopinst.value
  600.  
  601.     def marker(self):
  602.         stack = self.stack
  603.         mark = self.mark
  604.         k = len(stack)-1
  605.         while stack[k] is not mark: k = k-1
  606.         return k
  607.  
  608.     dispatch = {}
  609.  
  610.     def load_eof(self):
  611.         raise EOFError
  612.     dispatch[''] = load_eof
  613.  
  614.     def load_persid(self):
  615.         pid = self.readline()[:-1]
  616.         self.append(self.persistent_load(pid))
  617.     dispatch[PERSID] = load_persid
  618.  
  619.     def load_binpersid(self):
  620.         stack = self.stack
  621.  
  622.         pid = stack[-1]
  623.         del stack[-1]
  624.  
  625.         self.append(self.persistent_load(pid))
  626.     dispatch[BINPERSID] = load_binpersid
  627.  
  628.     def load_none(self):
  629.         self.append(None)
  630.     dispatch[NONE] = load_none
  631.  
  632.     def load_int(self):
  633.         data = self.readline()
  634.         try:
  635.             self.append(int(data))
  636.         except ValueError:
  637.             self.append(long(data))
  638.     dispatch[INT] = load_int
  639.  
  640.     def load_binint(self):
  641.         self.append(mloads('i' + self.read(4)))
  642.     dispatch[BININT] = load_binint
  643.  
  644.     def load_binint1(self):
  645.         self.append(mloads('i' + self.read(1) + '\000\000\000'))
  646.     dispatch[BININT1] = load_binint1
  647.  
  648.     def load_binint2(self):
  649.         self.append(mloads('i' + self.read(2) + '\000\000'))
  650.     dispatch[BININT2] = load_binint2
  651.  
  652.     def load_long(self):
  653.         self.append(long(self.readline()[:-1], 0))
  654.     dispatch[LONG] = load_long
  655.  
  656.     def load_float(self):
  657.         self.append(float(self.readline()[:-1]))
  658.     dispatch[FLOAT] = load_float
  659.  
  660.     def load_binfloat(self, unpack=struct.unpack):
  661.         self.append(unpack('>d', self.read(8))[0])
  662.     dispatch[BINFLOAT] = load_binfloat
  663.  
  664.     def load_string(self):
  665.         rep = self.readline()[:-1]
  666.         if not self._is_string_secure(rep):
  667.             raise ValueError, "insecure string pickle"
  668.         self.append(eval(rep,
  669.                          {'__builtins__': {}})) # Let's be careful
  670.     dispatch[STRING] = load_string
  671.  
  672.     def _is_string_secure(self, s):
  673.         """Return true if s contains a string that is safe to eval
  674.  
  675.         The definition of secure string is based on the implementation
  676.         in cPickle.  s is secure as long as it only contains a quoted
  677.         string and optional trailing whitespace.
  678.         """
  679.         q = s[0]
  680.         if q not in ("'", '"'):
  681.             return 0
  682.         # find the closing quote
  683.         offset = 1
  684.         i = None
  685.         while 1:
  686.             try:
  687.                 i = s.index(q, offset)
  688.             except ValueError:
  689.                 # if there is an error the first time, there is no
  690.                 # close quote
  691.                 if offset == 1:
  692.                     return 0
  693.             if s[i-1] != '\\':
  694.                 break
  695.             # check to see if this one is escaped
  696.             nslash = 0
  697.             j = i - 1
  698.             while j >= offset and s[j] == '\\':
  699.                 j = j - 1
  700.                 nslash = nslash + 1
  701.             if nslash % 2 == 0:
  702.                 break
  703.             offset = i + 1
  704.         for c in s[i+1:]:
  705.             if ord(c) > 32:
  706.                 return 0
  707.         return 1
  708.  
  709.     def load_binstring(self):
  710.         len = mloads('i' + self.read(4))
  711.         self.append(self.read(len))
  712.     dispatch[BINSTRING] = load_binstring
  713.  
  714.     def load_unicode(self):
  715.         self.append(unicode(self.readline()[:-1],'raw-unicode-escape'))
  716.     dispatch[UNICODE] = load_unicode
  717.  
  718.     def load_binunicode(self):
  719.         len = mloads('i' + self.read(4))
  720.         self.append(unicode(self.read(len),'utf-8'))
  721.     dispatch[BINUNICODE] = load_binunicode
  722.  
  723.     def load_short_binstring(self):
  724.         len = mloads('i' + self.read(1) + '\000\000\000')
  725.         self.append(self.read(len))
  726.     dispatch[SHORT_BINSTRING] = load_short_binstring
  727.  
  728.     def load_tuple(self):
  729.         k = self.marker()
  730.         self.stack[k:] = [tuple(self.stack[k+1:])]
  731.     dispatch[TUPLE] = load_tuple
  732.  
  733.     def load_empty_tuple(self):
  734.         self.stack.append(())
  735.     dispatch[EMPTY_TUPLE] = load_empty_tuple
  736.  
  737.     def load_empty_list(self):
  738.         self.stack.append([])
  739.     dispatch[EMPTY_LIST] = load_empty_list
  740.  
  741.     def load_empty_dictionary(self):
  742.         self.stack.append({})
  743.     dispatch[EMPTY_DICT] = load_empty_dictionary
  744.  
  745.     def load_list(self):
  746.         k = self.marker()
  747.         self.stack[k:] = [self.stack[k+1:]]
  748.     dispatch[LIST] = load_list
  749.  
  750.     def load_dict(self):
  751.         k = self.marker()
  752.         d = {}
  753.         items = self.stack[k+1:]
  754.         for i in range(0, len(items), 2):
  755.             key = items[i]
  756.             value = items[i+1]
  757.             d[key] = value
  758.         self.stack[k:] = [d]
  759.     dispatch[DICT] = load_dict
  760.  
  761.     def load_inst(self):
  762.         k = self.marker()
  763.         args = tuple(self.stack[k+1:])
  764.         del self.stack[k:]
  765.         module = self.readline()[:-1]
  766.         name = self.readline()[:-1]
  767.         klass = self.find_class(module, name)
  768.         instantiated = 0
  769.         if (not args and type(klass) is ClassType and
  770.             not hasattr(klass, "__getinitargs__")):
  771.             try:
  772.                 value = _EmptyClass()
  773.                 value.__class__ = klass
  774.                 instantiated = 1
  775.             except RuntimeError:
  776.                 # In restricted execution, assignment to inst.__class__ is
  777.                 # prohibited
  778.                 pass
  779.         if not instantiated:
  780.             try:
  781.                 if not hasattr(klass, '__safe_for_unpickling__'):
  782.                     raise UnpicklingError('%s is not safe for unpickling' %
  783.                                           klass)
  784.                 value = apply(klass, args)
  785.             except TypeError, err:
  786.                 raise TypeError, "in constructor for %s: %s" % (
  787.                     klass.__name__, str(err)), sys.exc_info()[2]
  788.         self.append(value)
  789.     dispatch[INST] = load_inst
  790.  
  791.     def load_obj(self):
  792.         stack = self.stack
  793.         k = self.marker()
  794.         klass = stack[k + 1]
  795.         del stack[k + 1]
  796.         args = tuple(stack[k + 1:])
  797.         del stack[k:]
  798.         instantiated = 0
  799.         if (not args and type(klass) is ClassType and
  800.             not hasattr(klass, "__getinitargs__")):
  801.             try:
  802.                 value = _EmptyClass()
  803.                 value.__class__ = klass
  804.                 instantiated = 1
  805.             except RuntimeError:
  806.                 # In restricted execution, assignment to inst.__class__ is
  807.                 # prohibited
  808.                 pass
  809.         if not instantiated:
  810.             value = apply(klass, args)
  811.         self.append(value)
  812.     dispatch[OBJ] = load_obj
  813.  
  814.     def load_global(self):
  815.         module = self.readline()[:-1]
  816.         name = self.readline()[:-1]
  817.         klass = self.find_class(module, name)
  818.         self.append(klass)
  819.     dispatch[GLOBAL] = load_global
  820.  
  821.     def find_class(self, module, name):
  822.         __import__(module)
  823.         mod = sys.modules[module]
  824.         klass = getattr(mod, name)
  825.         return klass
  826.  
  827.     def load_reduce(self):
  828.         stack = self.stack
  829.  
  830.         callable = stack[-2]
  831.         arg_tup  = stack[-1]
  832.         del stack[-2:]
  833.  
  834.         if type(callable) is not ClassType:
  835.             if not safe_constructors.has_key(callable):
  836.                 try:
  837.                     safe = callable.__safe_for_unpickling__
  838.                 except AttributeError:
  839.                     safe = None
  840.  
  841.                 if not safe:
  842.                     raise UnpicklingError, "%s is not safe for " \
  843.                                            "unpickling" % callable
  844.  
  845.         if arg_tup is None:
  846.             value = callable.__basicnew__()
  847.         else:
  848.             value = apply(callable, arg_tup)
  849.         self.append(value)
  850.     dispatch[REDUCE] = load_reduce
  851.  
  852.     def load_pop(self):
  853.         del self.stack[-1]
  854.     dispatch[POP] = load_pop
  855.  
  856.     def load_pop_mark(self):
  857.         k = self.marker()
  858.         del self.stack[k:]
  859.     dispatch[POP_MARK] = load_pop_mark
  860.  
  861.     def load_dup(self):
  862.         self.append(self.stack[-1])
  863.     dispatch[DUP] = load_dup
  864.  
  865.     def load_get(self):
  866.         self.append(self.memo[self.readline()[:-1]])
  867.     dispatch[GET] = load_get
  868.  
  869.     def load_binget(self):
  870.         i = mloads('i' + self.read(1) + '\000\000\000')
  871.         self.append(self.memo[`i`])
  872.     dispatch[BINGET] = load_binget
  873.  
  874.     def load_long_binget(self):
  875.         i = mloads('i' + self.read(4))
  876.         self.append(self.memo[`i`])
  877.     dispatch[LONG_BINGET] = load_long_binget
  878.  
  879.     def load_put(self):
  880.         self.memo[self.readline()[:-1]] = self.stack[-1]
  881.     dispatch[PUT] = load_put
  882.  
  883.     def load_binput(self):
  884.         i = mloads('i' + self.read(1) + '\000\000\000')
  885.         self.memo[`i`] = self.stack[-1]
  886.     dispatch[BINPUT] = load_binput
  887.  
  888.     def load_long_binput(self):
  889.         i = mloads('i' + self.read(4))
  890.         self.memo[`i`] = self.stack[-1]
  891.     dispatch[LONG_BINPUT] = load_long_binput
  892.  
  893.     def load_append(self):
  894.         stack = self.stack
  895.         value = stack[-1]
  896.         del stack[-1]
  897.         list = stack[-1]
  898.         list.append(value)
  899.     dispatch[APPEND] = load_append
  900.  
  901.     def load_appends(self):
  902.         stack = self.stack
  903.         mark = self.marker()
  904.         list = stack[mark - 1]
  905.         for i in range(mark + 1, len(stack)):
  906.             list.append(stack[i])
  907.  
  908.         del stack[mark:]
  909.     dispatch[APPENDS] = load_appends
  910.  
  911.     def load_setitem(self):
  912.         stack = self.stack
  913.         value = stack[-1]
  914.         key = stack[-2]
  915.         del stack[-2:]
  916.         dict = stack[-1]
  917.         dict[key] = value
  918.     dispatch[SETITEM] = load_setitem
  919.  
  920.     def load_setitems(self):
  921.         stack = self.stack
  922.         mark = self.marker()
  923.         dict = stack[mark - 1]
  924.         for i in range(mark + 1, len(stack), 2):
  925.             dict[stack[i]] = stack[i + 1]
  926.  
  927.         del stack[mark:]
  928.     dispatch[SETITEMS] = load_setitems
  929.  
  930.     def load_build(self):
  931.         stack = self.stack
  932.         value = stack[-1]
  933.         del stack[-1]
  934.         inst = stack[-1]
  935.         try:
  936.             setstate = inst.__setstate__
  937.         except AttributeError:
  938.             try:
  939.                 inst.__dict__.update(value)
  940.             except RuntimeError:
  941.                 # XXX In restricted execution, the instance's __dict__ is not
  942.                 # accessible.  Use the old way of unpickling the instance
  943.                 # variables.  This is a semantic different when unpickling in
  944.                 # restricted vs. unrestricted modes.
  945.                 for k, v in value.items():
  946.                     setattr(inst, k, v)
  947.         else:
  948.             setstate(value)
  949.     dispatch[BUILD] = load_build
  950.  
  951.     def load_mark(self):
  952.         self.append(self.mark)
  953.     dispatch[MARK] = load_mark
  954.  
  955.     def load_stop(self):
  956.         value = self.stack[-1]
  957.         del self.stack[-1]
  958.         raise _Stop(value)
  959.     dispatch[STOP] = load_stop
  960.  
  961. # Helper class for load_inst/load_obj
  962.  
  963. class _EmptyClass:
  964.     pass
  965.  
  966. # Shorthands
  967.  
  968. try:
  969.     from cStringIO import StringIO
  970. except ImportError:
  971.     from StringIO import StringIO
  972.  
  973. def dump(object, file, bin = 0):
  974.     Pickler(file, bin).dump(object)
  975.  
  976. def dumps(object, bin = 0):
  977.     file = StringIO()
  978.     Pickler(file, bin).dump(object)
  979.     return file.getvalue()
  980.  
  981. def load(file):
  982.     return Unpickler(file).load()
  983.  
  984. def loads(str):
  985.     file = StringIO(str)
  986.     return Unpickler(file).load()
  987.